<template>
    <div class="login">
        <!-- 顶部导航栏 -->
        <header>
            <van-nav-bar :title="isTitle ? '登录' : '注册'" left-arrow @click-left="onClickLeft">
                <template #right>
                    <van-icon name="ellipsis" size="18" />
                </template>
            </van-nav-bar>
        </header>
        <!-- logo -->
        <div class="logo" style="text-align: center;padding: 20px 0;">
            <van-image round width="6rem" height="6rem" src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg" />
        </div>
        <!-- 表单  -->
        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
                    :rules="[{ required: true, message: '请填写手机号' }]" />
                <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
                    :rules="[{ required: true, message: '请填写密码' }]" />
            </van-cell-group>

            <div style="margin: 16px;">
                <p class="link-register" @click="isTitle = !isTitle">{{ isTitle ? '立即注册' : '已有账号，立即登录' }}</p>
                <van-button round block type="primary" native-type="submit">
                    {{ isTitle ? '登录' : '注册' }}
                </van-button>
            </div>
        </van-form>



    </div>
</template>

<script setup>
import { ref, reactive, toRefs } from 'vue';
import { register, login } from '@/api/index.js';
import { showNotify } from 'vant'
import { useRouter } from 'vue-router';
let router = useRouter()
const onClickLeft = () => history.back();
let userInfo = reactive({
    username: '18222899182',
    password: '123456',
    isTitle: true //控制是登录还是注册 true表示登录
})
let { username, password, isTitle } = toRefs(userInfo)
const onSubmit = () => {
    if (userInfo.isTitle) {
        login(userInfo.username, userInfo.password).then(data => {
            if (data.resultCode == 200) {
                localStorage.setItem('mltoken', data.data);
                router.replace('/home');
                showNotify({
                    type: 'success',
                    message: '登录成功'
                })
            }
        })
    } else {
        register(userInfo.username, userInfo.password).then(data => {
            if (data.resultCode == 200) {
                showNotify({
                    type: 'success',
                    message: '注册成功'
                })
            };
            userInfo.isTitle = true;//注册成功后开始登录
        })
    }
}


</script>

<style scoped>
header {
    height: 50px;
    border-bottom: 1px solid #ccc;
    box-sizing: border-box;
}

.link-register {
    float: left;
    font-size: 0.37333rem;
    margin-bottom: 0.53333rem;
    color: #1989fa;
    display: inline-block;
}

.van-button--round {
    background: rgb(27, 174, 174) !important;
    border-color: rgb(27, 174, 174) !important;
}
</style>